<?

if (empty($_SERVER['DOCUMENT_ROOT'])) {
	$_SERVER['DOCUMENT_ROOT'] = "/var/www/vhosts/geographs.org/httpdocs/";
}

include($_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php');
include($_SERVER['DOCUMENT_ROOT'].'/portals/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');

if (false) {
	init_session();

	if (empty($_SESSION['user_id'])) {
		include($_SERVER['DOCUMENT_ROOT'].'/portals/login.inc.php');
		exit;
	}
}

include($_SERVER['DOCUMENT_ROOT'].'/portals/filter.libs.php');


$portal_id = intval(@$_GET['id']);
if ($portal_id) {
	
	
	$all = getCol("SELECT gridimage_id FROM p2.gridimage{$portal_id}_bi_view");
	
	foreach ($all as $gid) {

		$words = getCol("SELECT word FROM libpuzzleword WHERE gridimage_id = $gid");

		if (!empty($words)) {
		

			$images = getAssoc("SELECT gridimage_id,COUNT(*) c FROM libpuzzleword WHERE `word` IN (".implode(',',$words).") AND gridimage_id != $gid GROUP BY gridimage_id ORDER BY NULL");

			$score = array_sum($images)+0; //total
			
			
			queryExecute("REPLACE INTO gridimage_similarity SET portal_id = $portal_id, gridimage_id = $gid, similarity = $score, created = NOW()");

		}
		
	}
	print "fetching sort...<br>\n";flush();
	$all = getCol("SELECT gridimage_id FROM gridimage_similarity WHERE portal_id = $portal_id ORDER BY similarity,gridimage_id");
	
	foreach ($all as $idx => $gid) {
		queryExecute("UPDATE gridimage_similarity SET rank = ".($idx+1)." WHERE portal_id = $portal_id AND gridimage_id = $gid");
	}
}
	
print "done";
